package com.yubest.demo.handler.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.yubest.demo.handler.BusinessException;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Author hweiyu
 * @Description
 * @Date 2021/8/12 10:28
 */
public class ZipHandler extends BaseHandler {
    @Override
    public String getPassword(String path, String password) {
        InputStream is = null;
        try {
            ZipFile zipFile = new ZipFile(path);
            if (zipFile.isEncrypted()) {
                zipFile.setPassword(password.toCharArray());
            }
            List<FileHeader> fileHeaders = zipFile.getFileHeaders();
            if (CollectionUtil.isEmpty(fileHeaders)) {
                throw new BusinessException("压缩文件内容为空");
            }
            for (FileHeader fileHeader : fileHeaders) {
                if (!fileHeader.isDirectory()) {
                    is = zipFile.getInputStream(fileHeader);
                    byte[] b = new byte[1024];
                    while (is.read(b) != -1) {
                        //Do nothing as we just want to verify password
                    }
                    return password;
                }
            }
        } catch (ZipException e) {
//            ZipException.Type.WRONG_PASSWORD == e.getType()
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {

                }
            }
        }
        return null;
    }
}
